#!/command/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# PulseAudio socket monitor service
# ==============================================================================

bashio::log.info "Starting PulseAudio socket monitor..."

while true; do
    if [ -S "/run/audio/pulse.sock" ]; then
        bashio::log.debug "Monitoring /run/audio/pulse.sock for changes..."
        if ! inotifywait -q -e delete_self "/run/audio/pulse.sock"; then
            bashio::log.warning "inotifywait failed, retrying in 5 seconds..."
            sleep 5
            continue
        fi

        bashio::log.info "PulseAudio socket deleted, restarting VLC service..."
        s6-rc -d change vlc
        sleep 1
        s6-rc -u change vlc

        bashio::log.info "VLC service restarted"
    else
        bashio::log.debug "PulseAudio socket not found, waiting 5 seconds..."
        sleep 5
    fi
done
